<template>
  <div id="app" class="model-evaluation-page">
    <header class="app-header">
      <h1>模型评估与比较</h1>
      <p>深入分析模型性能，进行多维度对比</p>
    </header>

    <div class="main-content-container">
      <section class="section-block model-comparison-selection">
        <h2 class="section-title">选择模型进行比较</h2>
        <div class="model-select-chips">
          <div
            v-for="model in availableModels"
            :key="model.id"
            :class="['model-chip', { 'selected': selectedModels.includes(model.id) }]"
            @click="toggleModelSelection(model.id)"
          >
            {{ model.name }}
          </div>
        </div>
        <p v-if="selectedModels.length === 0" class="info-message">请选择至少一个模型进行评估。</p>
      </section>

      <hr class="divider" />

      <div v-if="selectedModels.length > 0" class="comparison-details-grid">
        <div class="overview-column">
          <section class="section-block">
            <h2 class="section-title">核心评估指标概览</h2>
            <div class="metrics-grid">
              <div class="metric-card">
                <span class="metric-value">{{ overallMetrics.mae ? overallMetrics.mae.toFixed(3) : 'N/A' }}</span>
                <span class="metric-label">平均绝对误差 (MAE)</span>
              </div>
              <div class="metric-card">
                <span class="metric-value">{{ overallMetrics.mse ? overallMetrics.mse.toFixed(3) : 'N/A' }}</span>
                <span class="metric-label">均方误差 (MSE)</span>
              </div>
              <div class="metric-card">
                <span class="metric-value">{{ overallMetrics.rmse ? overallMetrics.rmse.toFixed(3) : 'N/A' }}</span>
                <span class="metric-label">均方根误差 (RMSE)</span>
              </div>
              <div class="metric-card">
                <span class="metric-value">{{ overallMetrics.r2 ? overallMetrics.r2.toFixed(3) : 'N/A' }}</span>
                <span class="metric-label">决定系数 (R²)</span>
              </div>
            </div>
          </section>

          <section class="section-block chart-container">
            <h2 class="section-title">误差分布图</h2>
            <div id="errorDistributionChart" class="chart-placeholder">
              <p class="chart-tip">此处显示误差分布图 (例如：直方图)</p>
            </div>
          </section>
        </div>

        <div class="charts-and-table-column">
          <section class="section-block chart-container">
            <h2 class="section-title">预测值 vs 真实值</h2>
            <div id="predictionVsActualChart" class="chart-placeholder">
              <p class="chart-tip">此处显示预测值与真实值对比图 (例如：散点图)</p>
            </div>
          </section>

          <section class="section-block chart-container">
            <h2 class="section-title">训练损失曲线</h2>
            <div id="lossCurveChart" class="chart-placeholder">
              <p class="chart-tip">此处显示训练损失随轮数变化曲线图</p>
            </div>
          </section>

          <hr class="divider" />

          <section class="section-block comparison-table-section">
            <h2 class="section-title">模型性能详细对比</h2>
            <div class="table-responsive">
              <table class="data-table comparison-table">
                <thead>
                  <tr>
                    <th>指标</th>
                    <th v-for="modelId in selectedModels" :key="modelId">
                      {{ availableModels.find(m => m.id === modelId)?.name }}
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>MAE</td>
                    <td v-for="modelId in selectedModels" :key="modelId">
                      {{ getMetricForModel(modelId, 'mae') }}
                    </td>
                  </tr>
                  <tr>
                    <td>MSE</td>
                    <td v-for="modelId in selectedModels" :key="modelId">
                      {{ getMetricForModel(modelId, 'mse') }}
                    </td>
                  </tr>
                  <tr>
                    <td>RMSE</td>
                    <td v-for="modelId in selectedModels" :key="modelId">
                      {{ getMetricForModel(modelId, 'rmse') }}
                    </td>
                  </tr>
                  <tr>
                    <td>R²</td>
                    <td v-for="modelId in selectedModels" :key="modelId">
                      {{ getMetricForModel(modelId, 'r2') }}
                    </td>
                  </tr>
                  <tr>
                    <td>训练时长 (秒)</td>
                    <td v-for="modelId in selectedModels" :key="modelId">
                      {{ getMetricForModel(modelId, 'trainingTime') }}
                    </td>
                  </tr>
                  </tbody>
              </table>
            </div>
          </section>
        </div>
      </div>

      <div v-else class="empty-state-card">
        <p>请选择左侧的模型，查看其评估结果并进行比较。</p>
        <p>支持多选，以便更直观地对比不同模型的优劣。</p>
      </div>
    </div>
  </div>
</template>

<script>
// Mock data for demonstration purposes
const mockModelsData = [
  {
    id: 'model-a',
    name: 'Transformer v1.0',
    metrics: {
      mae: 0.123,
      mse: 0.021,
      rmse: 0.145,
      r2: 0.95,
      trainingTime: 3600, // seconds
      lossCurve: [1.0, 0.8, 0.6, 0.4, 0.3, 0.25, 0.22, 0.2, 0.18, 0.17],
      predictions: Array.from({ length: 100 }, (_, i) => ({
        actual: parseFloat((Math.random() * 100).toFixed(2)),
        predicted: parseFloat(((Math.random() * 100) * (i / 100 + 0.5)).toFixed(2)), // simulate some correlation
        error: parseFloat((Math.random() * 5 - 2.5).toFixed(2))
      })),
    }
  },
  {
    id: 'model-b',
    name: 'LSTM v2.1',
    metrics: {
      mae: 0.155,
      mse: 0.030,
      rmse: 0.173,
      r2: 0.92,
      trainingTime: 2800,
      lossCurve: [1.2, 1.0, 0.8, 0.6, 0.5, 0.4, 0.35, 0.32, 0.3, 0.28],
      predictions: Array.from({ length: 100 }, (_, i) => ({
        actual: parseFloat((Math.random() * 100).toFixed(2)),
        predicted: parseFloat(((Math.random() * 100) * (i / 100 + 0.4)).toFixed(2)),
        error: parseFloat((Math.random() * 6 - 3).toFixed(2))
      })),
    }
  },
  {
    id: 'model-c',
    name: 'CNN-Seq v1.5',
    metrics: {
      mae: 0.130,
      mse: 0.023,
      rmse: 0.152,
      r2: 0.94,
      trainingTime: 1800,
      lossCurve: [0.9, 0.7, 0.5, 0.35, 0.28, 0.23, 0.2, 0.19, 0.18, 0.175],
      predictions: Array.from({ length: 100 }, (_, i) => ({
        actual: parseFloat((Math.random() * 100).toFixed(2)),
        predicted: parseFloat(((Math.random() * 100) * (i / 100 + 0.6)).toFixed(2)),
        error: parseFloat((Math.random() * 4 - 2).toFixed(2))
      })),
    }
  },
  {
    id: 'model-d',
    name: 'Custom Model v1.0',
    metrics: {
      mae: 0.180,
      mse: 0.040,
      rmse: 0.200,
      r2: 0.88,
      trainingTime: 4200,
      lossCurve: [1.5, 1.3, 1.1, 0.9, 0.7, 0.6, 0.55, 0.5, 0.48, 0.45],
      predictions: Array.from({ length: 100 }, (_, i) => ({
        actual: parseFloat((Math.random() * 100).toFixed(2)),
        predicted: parseFloat(((Math.random() * 100) * (i / 100 + 0.3)).toFixed(2)),
        error: parseFloat((Math.random() * 7 - 3.5).toFixed(2))
      })),
    }
  }
];

export default {
  name: 'ModelEvaluationPage',
  data() {
    return {
      availableModels: mockModelsData,
      selectedModels: [], // Stores IDs of selected models for comparison
    };
  },
  computed: {
    // Calculates average metrics for the first selected model or overall if multiple are selected (can be refined)
    overallMetrics() {
      if (this.selectedModels.length === 0) {
        return {};
      }
      const primaryModel = this.availableModels.find(m => m.id === this.selectedModels[0]);
      return primaryModel ? primaryModel.metrics : {};
    }
  },
  methods: {
    toggleModelSelection(modelId) {
      const index = this.selectedModels.indexOf(modelId);
      if (index > -1) {
        this.selectedModels.splice(index, 1); // Deselect
      } else {
        this.selectedModels.push(modelId); // Select
      }
      // Re-render charts when selection changes (in a real app)
      this.$nextTick(() => {
        this.renderCharts();
      });
    },
    getMetricForModel(modelId, metricKey) {
      const model = this.availableModels.find(m => m.id === modelId);
      if (model && model.metrics[metricKey] !== undefined) {
        return typeof model.metrics[metricKey] === 'number'
               ? model.metrics[metricKey].toFixed(3)
               : model.metrics[metricKey];
      }
      return 'N/A';
    },
    renderCharts() {
      // This is where you would initialize and update your ECharts instances
      // For demonstration, we just log a message.
      console.log('Rendering charts for selected models:', this.selectedModels);

      // Example of how you'd use ECharts (requires ECharts library installed)
      // import * as echarts from 'echarts';
      // if (this.selectedModels.length > 0) {
      //   const modelData = this.selectedModels.map(id => this.availableModels.find(m => m.id === id));

      //   // Chart 1: Error Distribution
      //   const errorChartDom = document.getElementById('errorDistributionChart');
      //   if (errorChartDom) {
      //     const errorChart = echarts.init(errorChartDom);
      //     // Prepare data for histogram/density plot of errors for selected models
      //     const errorData = modelData.map(model => ({
      //       name: model.name,
      //       data: model.metrics.predictions.map(p => p.error)
      //     }));
      //     const errorOption = { /* ECharts options for error distribution */ };
      //     errorChart.setOption(errorOption);
      //   }

      //   // Chart 2: Prediction vs Actual
      //   const pvAChartDom = document.getElementById('predictionVsActualChart');
      //   if (pvAChartDom) {
      //     const pvAChart = echarts.init(pvAChartDom);
      //     // Prepare data for scatter plot of predictions vs actual for selected models
      //     const pvAData = modelData.map(model => ({
      //       name: model.name,
      //       data: model.metrics.predictions.map(p => [p.actual, p.predicted])
      //     }));
      //     const pvAOption = { /* ECharts options for prediction vs actual */ };
      //     pvAChart.setOption(pvAOption);
      //   }

      //   // Chart 3: Loss Curve
      //   const lossChartDom = document.getElementById('lossCurveChart');
      //   if (lossChartDom) {
      //     const lossChart = echarts.init(lossChartDom);
      //     // Prepare data for line chart of loss curves for selected models
      //     const lossData = modelData.map(model => ({
      //       name: model.name,
      //       type: 'line',
      //       data: model.metrics.lossCurve
      //     }));
      //     const lossOption = {
      //       legend: { data: modelData.map(m => m.name) },
      //       xAxis: { type: 'category', name: 'Epoch' },
      //       yAxis: { type: 'value', name: 'Loss' },
      //       series: lossData
      //     };
      //     lossChart.setOption(lossOption);
      //   }
      // } else {
      //   // Dispose charts if no models selected
      //   echarts.dispose(document.getElementById('errorDistributionChart'));
      //   echarts.dispose(document.getElementById('predictionVsActualChart'));
      //   echarts.dispose(document.getElementById('lossCurveChart'));
      // }
    }
  },
  mounted() {
    // Initial chart rendering if default models are selected or for an empty state
    this.renderCharts();
  },
  watch: {
    // Watch for changes in selectedModels to re-render charts
    selectedModels: {
      handler() {
        this.renderCharts();
      },
      deep: true // Watch for changes inside the array
    }
  }
};
</script>

<style>
/* Base Styles & Typography - Mostly inherited from previous page, with minor adjustments */
body {
  font-family: 'Inter', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  margin: 0;
  /* padding: 30px; */
  background-color: #f0f2f5;
  color: #333;
  line-height: 1.6;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.model-evaluation-page {
  max-width: 1400px; /* Wider for more complex data display */
  margin: 0 auto;
  box-sizing: border-box;
}

.app-header {
  text-align: center;
  margin-bottom: 40px;
  background: linear-gradient(135deg, #007bff 0%, #0056b3 100%); /* Slightly different gradient for variety */
  color: white;
  padding: 30px 20px;
  border-radius: 12px;
  box-shadow: 0 8px 25px rgba(0, 86, 179, 0.2);
}

.app-header h1 {
  font-size: 2.8em;
  margin-bottom: 10px;
  font-weight: 700;
}

.app-header p {
  font-size: 1.1em;
  opacity: 0.9;
  margin-top: 0;
}

/* Section and Sub-section Styling (reused and adapted) */
.section-block {
  margin-bottom: 30px; /* Slightly less margin as content is denser */
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05); /* Lighter shadow for blocks */
  padding: 30px;
}

.section-title {
  font-size: 1.8em;
  color: #2c3e50;
  margin-bottom: 25px;
  border-bottom: 2px solid #e9ecef;
  padding-bottom: 15px;
  font-weight: 600;
  text-align: left;
}

.divider {
  border: none;
  border-top: 1px dashed #e0e0e0;
  margin: 30px 0;
}

/* Model Selection Chips */
.model-comparison-selection {
  padding-bottom: 20px;
}

.model-select-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 15px;
}

.model-chip {
  padding: 10px 20px;
  background-color: #e9eff5;
  border: 1px solid #d4dbe2;
  border-radius: 25px;
  cursor: pointer;
  font-size: 0.95em;
  color: #555;
  transition: all 0.3s ease;
  white-space: nowrap; /* Prevent wrapping */
}

.model-chip:hover {
  background-color: #dbe4ec;
  border-color: #b0c2d3;
}

.model-chip.selected {
  background-color: #007bff;
  color: white;
  border-color: #007bff;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
  transform: translateY(-2px);
}

.info-message {
  color: #888;
  font-size: 0.9em;
  margin-top: 20px;
  padding-left: 10px;
}

/* Main Comparison Details Grid */
.comparison-details-grid {
  display: grid;
  grid-template-columns: 1fr; /* Default to single column */
  gap: 30px;
}

@media (min-width: 1024px) { /* Two columns on larger screens */
  .comparison-details-grid {
    grid-template-columns: 1fr 2fr; /* Left column for overview, right for charts/table */
  }
}

/* Metrics Grid */
.metrics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.metric-card {
  background-color: #f7f9fc;
  border: 1px solid #e0e7ff;
  border-radius: 10px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.metric-value {
  font-size: 2.2em;
  font-weight: 700;
  color: #007bff;
  display: block;
  margin-bottom: 5px;
}

.metric-label {
  font-size: 0.9em;
  color: #666;
  display: block;
}

/* Chart Containers */
.chart-container {
  min-height: 350px; /* Minimum height for charts */
  display: flex;
  flex-direction: column;
}

.chart-placeholder {
  flex-grow: 1; /* Make placeholder fill available space */
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fcfdfe;
  border: 1px dashed #e9ecef;
  border-radius: 8px;
  margin-top: 15px;
  min-height: 250px; /* Ensure charts have a base height */
}

.chart-tip {
    color: #999;
    font-style: italic;
    font-size: 0.9em;
    text-align: center;
    padding: 20px;
}

/* Comparison Table */
.comparison-table-section {
  margin-top: 30px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

.data-table th,
.data-table td {
  padding: 15px 20px;
  text-align: left;
  border-bottom: 1px solid #f0f2f5;
  white-space: nowrap; /* Prevent content from wrapping in cells */
}

.data-table th {
  background-color: #f5f8fa;
  font-weight: bold;
  color: #555;
  text-transform: uppercase;
  font-size: 0.9em;
}

.data-table tr:last-child td {
  border-bottom: none;
}

.comparison-table tbody tr:hover {
  background-color: #f8faff;
}

.comparison-table td:first-child {
  font-weight: 500;
  color: #333;
}


/* Empty State */
.empty-state-card {
  text-align: center;
  padding: 50px;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  color: #666;
  font-size: 1.1em;
  margin-top: 30px;
}

.empty-state-card p:first-child {
    font-weight: bold;
    color: #444;
    margin-bottom: 10px;
}


/* Responsive Adjustments */
@media (max-width: 1023px) {
  .comparison-details-grid {
    grid-template-columns: 1fr; /* Stack columns */
  }
  .section-title {
    text-align: center; /* Center titles when stacked */
  }
  .divider {
    display: block; /* Show dividers between sections when stacked */
  }
}

@media (max-width: 768px) {
  body {
    padding: 15px;
  }
  .app-header {
    padding: 20px 15px;
  }
  .app-header h1 {
    font-size: 2em;
  }
  .app-header p {
    font-size: 0.9em;
  }
  .section-block {
    padding: 20px;
  }
  .metrics-grid {
    grid-template-columns: 1fr; /* Stack metrics on very small screens */
  }
  .metric-value {
    font-size: 1.8em;
  }
  .model-chip {
    padding: 8px 15px;
    font-size: 0.9em;
  }
}
</style>